#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author : gao
# Time : 2020/7/8 22:46

"""
    文件说明：数据计算
"""

import numpy as np
import CreateData as cd

from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt


def sigmoid(inX):
    return 1.0 / (1 + np.exp(-inX))


# def sigmoid(inX):
#     # return 1.0/(1+exp(-inX))
#     # 优化
#     if inX >= 0:
#         return 1.0 / (1 + np.exp(-inX))
#     else:
#         return np.exp(inX) / (1 + np.exp(inX))
#
#
# def sigmoidVector(x):
#     '''
#     计算向量的sigmoid
#     :param x:
#     :return:
#     '''
#     n,m = x.shape
#     res = np.zeros((m,1))
#     index =0
#     for i in x[0]:
#         res[index][0] =sigmoid(i)
#     return res


def getWByGradientDescent(dataMatIn, classLabels):
    '''
    计算权重向量
    :param dataMatIn: xi 为一行的 k行的数据矩阵(以list形式的)
    :param classLabels: xi 对应的标签 yi（以list形式的）
    :return: w向量
    '''
    dataMatrix = np.mat(dataMatIn)  # 转换成numpy的mat
    labelMat = np.mat(classLabels).transpose()  # 转换成numpy的mat,并进行转置
    m, n = np.shape(dataMatrix)  # 返回dataMatrix的大小。m为行数,n为列数。
    alpha = 0.001  # 移动步长,也就是学习速率,控制更新的幅度。
    maxCycles = 500000  # 最大迭代次数
    weights = np.ones((n, 1))
    for k in range(maxCycles):
        h = sigmoid(dataMatrix * weights)  # 梯度上升矢量化公式
        error = labelMat - h
        weights = weights + alpha * dataMatrix.transpose() * error
    return weights.getA()


'''
Parameters:
    weights - 权重参数数组
Returns:
    无
'''


# 函数说明:绘制数据集
def plotBestFit(weights):
    dataMat, labelMat = cd.loadDataSet()                                   #加载数据集
    dataArr = np.array(dataMat)                                         #转换成numpy的array数组
    n = np.shape(dataMat)[0]                                            #数据个数
    xcord1 = []; ycord1 = []                                            #正样本
    xcord2 = []; ycord2 = []                                            #负样本
    for i in range(n):                                                  #根据数据集标签进行分类
        if int(labelMat[i]) == 1:
            xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])    #1为正样本
        else:
            xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])    #0为负样本
    fig = plt.figure()
    ax = fig.add_subplot(111)                                           #添加subplot
    ax.scatter(xcord1, ycord1, s = 20, c = 'red', marker = 's',alpha=.5)#绘制正样本
    ax.scatter(xcord2, ycord2, s = 20, c = 'green',alpha=.5)            #绘制负样本
    x = np.arange(-3.0, 3.0, 0.1)
    y = (-weights[0] - weights[1] * x) / weights[2]
    ax.plot(x, y)
    plt.title('BestFit')                                                #绘制title
    plt.xlabel('X1'); plt.ylabel('X2')                                  #绘制label
    plt.show()


if __name__ == '__main__':
    dataMat, labelMat = cd.loadDataSet()
    weights = getWByGradientDescent(np.array(dataMat), labelMat)
    plotBestFit(weights)
